using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using BW.WMS.OperationKanban.WCL;
using BW.WMS.OperationKanban.WCL.Dto.Input;
using BW.WMS.OperationKanban.WCL.Dto.Output;
using BW.WMS.CodeEnum;
using System.Collections.Generic; // Added for List

namespace BW.WMS.Controllers
{
    /// <summary>
    /// 货品管理控制器
    /// </summary>
    [RemoteService(Name = "GoodsManagement")]
    [Route("api/goods-management")]
    public class GoodsManagementController : AbpController
    {
        private readonly IGoodsManagementAppService _goodsManagementAppService;

        public GoodsManagementController(IGoodsManagementAppService goodsManagementAppService)
        {
            _goodsManagementAppService = goodsManagementAppService;
        }

        /// <summary>
        /// 获取货品列表
        /// </summary>
        [HttpGet("goods-list")]
        public async Task<ActionResult<List<GoodsOutput>>> GetGoodsListAsync(
            [FromQuery] string? goodsNameOrCode = null,
            [FromQuery] string? itemTypeId = null,
            [FromQuery] string? unitId = null,
            [FromQuery] float? status = null,
            [FromQuery] string? warehouseId = null,
            [FromQuery] string? locationId = null,
            [FromQuery] string? barcode = null,
            [FromQuery] string? itemSpec = null)
        {
            var input = new GoodsQueryInput
            {
                GoodsNameOrCode = goodsNameOrCode,
                ItemTypeId = itemTypeId,
                UnitId = unitId,
                Status = status,
                WarehouseId = warehouseId,
                LocationId = locationId,
                Barcode = barcode,
                ItemSpec = itemSpec
            };

            var result = await _goodsManagementAppService.GetGoodsListAsync(input);
            return Ok(result);
        }

        /// <summary>
        /// 获取货品列表 (POST方式)
        /// </summary>
        [HttpPost("goods-list")]
        public async Task<ActionResult<List<GoodsOutput>>> GetGoodsListPostAsync([FromBody] GoodsQueryInput? input)
        {
            try
            {
                // 如果input为null，创建一个默认的查询对象
                if (input == null)
                {
                    input = new GoodsQueryInput();
                }

                var result = await _goodsManagementAppService.GetGoodsListAsync(input);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "请求参数错误", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取库存汇总信息
        /// </summary>
        /// <returns>库存汇总</returns>
        [HttpGet("inventory-summary")]
        public async Task<InventorySummaryOutput> GetInventorySummaryAsync()
        {
            return await _goodsManagementAppService.GetInventorySummaryAsync();
        }

        /// <summary>
        /// 导出货品数据
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>导出文件</returns>
        [HttpPost("export")]
        public async Task<IActionResult> ExportGoodsDataAsync(GoodsQueryInput input)
        {
            var fileBytes = await _goodsManagementAppService.ExportGoodsDataAsync(input);
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "货品数据.xlsx");
        }

        /// <summary>
        /// 获取货品类型列表
        /// </summary>
        /// <returns>货品类型列表</returns>
        [HttpGet("item-types")]
        public async Task<Volo.Abp.Application.Dtos.ListResultDto<ItemTypeDto>> GetItemTypesAsync()
        {
            return await _goodsManagementAppService.GetItemTypesAsync();
        }

        /// <summary>
        /// 获取单位列表
        /// </summary>
        /// <returns>单位列表</returns>
        [HttpGet("units")]
        public async Task<ApiPaging<UnitDto>> GetUnitsAsync()
        {
            return await _goodsManagementAppService.GetUnitsAsync();
        }

        /// <summary>
        /// 获取仓库列表
        /// </summary>
        [HttpGet("warehouses")]
        public async Task<Volo.Abp.Application.Dtos.ListResultDto<WarehouseDto>> GetWarehousesAsync()
        {
            return await _goodsManagementAppService.GetWarehousesAsync();
        }

        /// <summary>
        /// 获取库位列表
        /// </summary>
        [HttpGet("locations")]
        public async Task<Volo.Abp.Application.Dtos.ListResultDto<LocationDto>> GetLocationsAsync([FromQuery] string warehouseId = null)
        {
            return await _goodsManagementAppService.GetLocationsAsync(warehouseId);
        }

        /// <summary>
        /// 获取库位下拉框数据
        /// </summary>
        [HttpGet("location-select")]
        public async Task<ActionResult<List<LocationSelectDto>>> GetLocationSelectListAsync([FromQuery] string warehouseId = null)
        {
            try
            {
                var result = await _goodsManagementAppService.GetLocationSelectListAsync(warehouseId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "获取库位下拉框数据失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        [HttpPost("refresh")]
        public async Task<bool> RefreshDataAsync()
        {
            return await _goodsManagementAppService.RefreshDataAsync();
        }

        /// <summary>
        /// 测试数据库连接
        /// </summary>
        [HttpGet("test-db")]
        public async Task<string> TestDatabaseConnectionAsync()
        {
            return await _goodsManagementAppService.TestDatabaseConnectionAsync();
        }

        /// <summary>
        /// 添加货品
        /// </summary>
        [HttpPost("add")]
        public async Task<ActionResult<GoodsOutput>> AddGoodsAsync([FromBody] AddGoodsInput? input)
        {
            try
            {
                if (input == null)
                {
                    return BadRequest(new { error = "请求参数不能为空" });
                }

                var result = await _goodsManagementAppService.AddGoodsAsync(input);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "添加货品失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 更新货品
        /// </summary>
        [HttpPut("update")]
        public async Task<ActionResult<GoodsOutput>> UpdateGoodsAsync([FromBody] UpdateGoodsInput? input)
        {
            try
            {
                if (input == null)
                {
                    return BadRequest(new { error = "请求参数不能为空" });
                }

                var result = await _goodsManagementAppService.UpdateGoodsAsync(input);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "更新货品失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 删除货品
        /// </summary>
        /// <param name="id">货品ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete/{id}")]
        public async Task<bool> DeleteGoodsAsync(Guid id)
        {
            return await _goodsManagementAppService.DeleteGoodsAsync(id);
        }

        /// <summary>
        /// 根据ID获取货品详情
        /// </summary>
        /// <param name="id">货品ID</param>
        /// <returns>货品详情</returns>
        [HttpGet("detail/{id}")]
        public async Task<GoodsOutput> GetGoodsByIdAsync(Guid id)
        {
            return await _goodsManagementAppService.GetGoodsByIdAsync(id);
        }

        /// <summary>
        /// 获取货品库存详情
        /// </summary>
        /// <param name="goodsId">货品ID</param>
        /// <returns>货品库存详情</returns>
        [HttpGet("inventory-detail/{goodsId}")]
        public async Task<ActionResult<GoodsInventoryDetailOutput>> GetGoodsInventoryDetailAsync(Guid goodsId)
        {
            try
            {
                var result = await _goodsManagementAppService.GetGoodsInventoryDetailAsync(goodsId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "获取货品库存详情失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取货品库存详情（按货品编号）
        /// </summary>
        /// <param name="itemId">货品编号</param>
        /// <returns>货品库存详情</returns>
        [HttpGet("inventory-detail-by-itemid/{itemId}")]
        public async Task<ActionResult<GoodsInventoryDetailOutput>> GetGoodsInventoryDetailByItemIdAsync(string itemId)
        {
            try
            {
                var result = await _goodsManagementAppService.GetGoodsInventoryDetailByItemIdAsync(itemId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "获取货品库存详情失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 导出货品库存明细
        /// </summary>
        /// <param name="goodsId">货品ID</param>
        /// <returns>导出文件</returns>
        [HttpGet("export-inventory-detail/{goodsId}")]
        public async Task<IActionResult> ExportGoodsInventoryDetailAsync(Guid goodsId)
        {
            try
            {
                var fileBytes = await _goodsManagementAppService.ExportGoodsInventoryDetailAsync(goodsId);
                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "货品库存明细.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = "导出货品库存明细失败", message = ex.Message });
            }
        }
    }
} 